package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.SHOP_GEO_KEY;
import static com.hmdp.utils.SystemConstants.DEFAULT_PAGE_SIZE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ShopMapper shopMapper;
    @Resource
    private CacheClient cacheClient;

    @Override
    public Result queryShopById(Long id) {
        // 缓存穿透
        // Shop shop = queryWithPassThrough(id);
        Shop shop = cacheClient.queryWithPassThrough(
                RedisConstants.CACHE_SHOP_KEY,
                id,
                Shop.class,
                this::getById,
                RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 缓存击穿
        // 逻辑过期
        // Shop shop = queryWithPassMutex(id);
        /*Shop shop = cacheClient.queryWithLogicalExpire(
                RedisConstants.CACHE_SHOP_KEY,
                id,
                Shop.class,
                this::getById,
                10L, TimeUnit.MINUTES);*/
        //Shop shop = queryWithLogicalExpire(id);
        if (shop == null){
            return Result.fail("店铺不存在! ");
        }
        return Result.ok(shop);
    }

    @Override
    @Transactional
    public void updateShop(Shop shop) {
        Long id = shop.getId();
        if (id == null) {
            Result.fail("店铺不能为空");
            return;
        }
        // 更新数据库
        updateById(shop);
        // 删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY + id);
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        // 如果不按照距离查询
        if (x == null || y == null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        // 按距离分页查询, 带上距离参数
        // 1. 获得参数
        int from = (current - 1) * DEFAULT_PAGE_SIZE; // 起始页
        int end = current * DEFAULT_PAGE_SIZE; // 最终页
        String key = SHOP_GEO_KEY + typeId;

        // 2. 查询redis 按照距离排序 分页。
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(
                key,
                GeoReference.fromCoordinate(x, y),
                new Distance(5000),
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));

        // 3. 解析结果
        if (results == null){
            return Result.ok();
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        if (list.size() <= from){
            // 没有页了
            return Result.ok();
        }
        // 3.1 截取需要的部分
        List<Long> ids = new ArrayList<>(list.size());
        Map<Long, Distance> distanceMap = new HashMap<>(list.size());
        list.stream().skip(from).forEach(result ->{
            String idStr = result.getContent().getName();
            ids.add(Long.valueOf(idStr));
            distanceMap.put(Long.valueOf(idStr),result.getDistance());
        });
        // 4. 根据ids查询数据库
        String idStr = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + idStr + ")").list();
        // 5. 赋值距离参数
        shops.forEach(shop -> shop.setDistance(distanceMap.get(shop.getId()).getValue()));
        // 6. 返回结果
        return Result.ok(shops);
    }


    public void saveShopToRedis(Long id, Long expireSecond){
        // 1.查询店铺信息
        Shop shop = getById(id);
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 2.封装逻辑时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSecond));
        // 3.写入redis
        stringRedisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }


    private Shop queryWithPassMutex(Long id){
        // 1 从redis查缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        // 1.1 存在 返回
        if (StrUtil.isNotBlank(shopJSON)){
            return JSONUtil.toBean(shopJSON, Shop.class);
        }
        // 3.2 判断缓存的值是不是为"null"
        if (shopJSON != null) {
            // 返回错误
            return null;
        }
        // 1.2 不存在 从数据库查
        Shop shop = null;
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        try {
            // 4. 缓存重建
            // 4.1 获得互斥锁
            boolean isLock = getLock(lockKey);
            // 4.2 失败 重试
            if (!isLock){
                Thread.sleep(50);
                return queryWithPassMutex(id);
            }
            // 4.3 成功 重建
            shop = getById(id);
            // 模拟延迟
            Thread.sleep(200);
            if (shop == null){
                // 3 解决缓存穿透
                // 3.1 不存在数据加入Redis缓存
                stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
                return null;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 4.4 释放锁
            unLock(lockKey);
        }
        // 1.2.1 存储到缓存
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 2 返回数据
        return shop;
    }

    /**
     * 使用 Redis setNX 实现互斥锁
     * @param key
     * @return
     */
    private boolean getLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }

    /**
     * 释放锁
     * @param key
     */
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }

    /* private Shop queryWithPassThrough(Long id){
        // 1 从redis查缓存
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shopJSON = stringRedisTemplate.opsForValue().get(key);
        // 1.1 存在 返回
        if (StrUtil.isNotBlank(shopJSON)){
            return JSONUtil.toBean(shopJSON, Shop.class);
        }
        // 3.2 判断缓存的值是不是为"null"
        if (shopJSON != null) {
            // 返回错误
            return null;
        }
        // 1.2 不存在 从数据库查
        Shop shop = getById(id);
        if (shop == null){
            // 3 解决缓存穿透
            // 3.1 不存在数据加入Redis缓存
            stringRedisTemplate.opsForValue().set(key,"",RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        // 1.2.1 存储到缓存
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        // 2 返回数据
        return shop;
    }*/
}
